const API_BASE_URL = 'http://localhost:3000/api';

export interface Message {
  id?: number;
  name: string;
  email: string;
  phone: string;
  content: string;
  created_at?: string;
}

export async function getMessages() {
  const response = await fetch(`${API_BASE_URL}/messages`);

  if (!response.ok) {
    throw new Error('获取留言失败');
  }

  return response.json();
}

export async function getMessageDetail(id: number) {
  const response = await fetch(`${API_BASE_URL}/messages/${id}`);

  if (!response.ok) {
    throw new Error('获取留言详情失败');
  }

  return response.json();
}

export async function submitMessage(message: Omit<Message, 'id' | 'created_at'>) {
  const response = await fetch(`${API_BASE_URL}/messages`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(message),
  });
  return await response.json();
}

export async function updateMessage(message: Message) {
  const response = await fetch(`${API_BASE_URL}/messages/${message.id}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(message),
  });
  return await response.json();
}

export async function deleteMessage(id: number) {
  const response = await fetch(`${API_BASE_URL}/messages/${id}`, {
    method: 'DELETE'
  });
  return await response.json();
}